import ArticleItem from '@/components/Articleltem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import { clearResultsAction, getResultsAction } from '@/store/action/search';
import { InfiniteScroll } from 'antd-mobile';
import { useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  // 2. 使用new URLSearchParams（search）
  const { search } = useLocation();
  const urlParams = new URLSearchParams(search);
  // 3. 通过get方法拿到查询字符串的值
  const keyword = urlParams.get('q') as string;

  const dispatch = useDispatch();

  // useEffect(() => {
  //   dispatch(getResultsAction(keyword));
  // }, [keyword, dispatch]);

  const { result } = useAppSelector((state) => state.search);

  // 卸载组件
  useEffect(() => {
    return () => {
      dispatch(clearResultsAction());
    };
  }, [dispatch]);
  // 用Ref保存请求page,
  const pageRef = useRef(0); //自动会加载数据，发送请求，所以可以去掉组件挂载时所发送的请求
  const handleLoadMore = async () => {
    pageRef.current = pageRef.current + 1;
    await dispatch(getResultsAction(keyword, pageRef.current));
  };
  // 页码*每一页的总数》数据组件长度，说明没有数据了
  const hasMore = pageRef.current * 10 <= result.length;
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {result.map((item) => {
          return <ArticleItem key={item.art_id} data={item} />;
        })}
        {/* <ArticleItem /> */}
        {/* 无限滚动 */}
        <InfiniteScroll loadMore={handleLoadMore} hasMore={hasMore} />
        {/* 不知道写什么就悬停属性上 */}
      </div>
    </div>
  );
}
